<?php
//Start Session
session_start();

//Include database connection details
require_once('DBConfigQuery.php');
require_once('GenFunctions.php');
require_once('../config.inc.php');
//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = FALSE;

//Sanitize the POST values
$login = clean($_POST['login'], $dbc);
$password = clean($_POST['password'], $dbc);

//Input Validations
if ($login == '') {
    $errmsg_arr[] = 'Login ID missing';
    $errflag = true;
}
if ($password == '') {
    $errmsg_arr[] = 'Password missing';
    $errflag = true;
}

//TODO: Send this to the LogIn Page
//If there are input validations, redirect back to the login form
if ($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("Location: ControlLogIn.php");
    exit();
}

//Create query
$q = sprintf($Q_AUserAType_AUserAPass, $login, $password);
$r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

//Check whether the query was successful or not
if ($r) {
    if (mysqli_num_rows($r) == 1) {
        //Login Successful
        session_regenerate_id();
        $member = mysqli_fetch_array ($r, MYSQLI_ASSOC); //mysql_fetch_assoc($r);
        $_SESSION['SESS_MEMBER_ID'] = $member['AdminUserId'];
        $_SESSION['SESS_USER_TYPE'] = $member['UserType'];

        //Free Result and DB
        mysqli_free_result($r);
        mysqli_close($dbc);

        session_write_close();
        header("Location: AdminIndex.php");
        exit();
    } else {
        //Login failed
        //Free Result and DB
        mysqli_free_result($r);
        mysqli_close($dbc);
        header("Location: ControlLogInFailed.php");
        exit();
    }
} else {
    //Free DB
    mysqli_close($dbc);
    die("Query failed");
}
?>